<?php
class Exts_Content_Videos {

	/** Servicio de video */
	private $_service;

	/** Servicios de video soportados */
	private $_services = array(
		'youtube', 'vimeo'
	);

	/**
	 * Parsea la url y devuelve un host valido.
	 *
	 * @param string $url
	 * @return string $service
	 */
	public function getServiceByUrl( $url ) {
		$properties = parse_url( $url );
		$result = array();
		preg_match(' /^([^\.]+){1,1}\.(.+)\./', $properties['host'], $result );
		if( isset( $result[2] )) {
			$this->_service = strtolower($result[2]);
			return $this->_service;
		}

		preg_match(' /(.+)\./', $properties['host'], $result );

		if( isset( $result[1] )) {
			$this->_service = strtolower($result[1]);
			return $this->_service;
		}

		throw new Exception( "La url no es correcta" );
	}

	public function getCode( $url ){
		$method = "getCodeFrom" . ucfirst( $this->_service);
		return $this->$method( $url );
	}

	public function getCodeFromYoutube( $url ) {
		$properties = parse_url($url );

		$pattern = '/v=(.*)/';
		preg_match( $pattern, $properties['query'], $result  );
		print_r($result);exit;
		if( isset( $result[1] )) {
			return $result[1];
		}
		throw new Exception ('No se pudo obtener el codigo de la url');
	}

	public function getCodeFromVimeo( $url ) {
		$properties = parse_url($url );
		//print_r($properties);exit;
		$pattern = '/\/(.*)$/';
		preg_match( $pattern, $properties['path'], $result  );

		if( isset( $result[1] )) {
			return $result[1];
		}
		throw new Exception ('No se pudo obtener el codigo de la url');
	}


	public function setServiceByUrl( $url ) {
		if( $this->serviceExists( $url )) {
			$this->_service = $this->getServiceByUrl( $url );
		}else{
			throw new Exception ( "No se encontro un servicio valido en los
				parametros que se pasaron" );
		}
	}

	/**
	 * Averiguamos que la url que recibimos como parametro contenga datos
	 * de youtubue o vimeo
	 *
	 * @param string $url
	 */
	public function serviceExists( $url ) {
		return (
			in_array(
				$this->getServiceByUrl( $url ), $this->_services
			)
		);
	}
}